﻿using UnityEngine;
using System.Collections;

public class ButterflyMovement : MonoBehaviour {
	
	Vector3 target;
	private Vector3 normalizeDir;
	private Renderer renderChild;
	Sprites spriteHandler;
	public Texture2D[] butterflies;
	float speed;
	public TweenPosition tweenPos;

	// Use this for initialization
	void Start () 
	{
		renderChild = transform.GetChild(0).renderer;
		spriteHandler = new Sprites(renderChild, new Vector2(210, 190), 0,0);
		spriteHandler.Play(new SpriteState(0, 2, 3, false));
		renderChild.material.mainTexture = butterflies[Random.Range(0, butterflies.Length)];
		target = Camera.main.ScreenToWorldPoint(randomPosition());
		target.z = transform.position.z;
		randomSpeed();
	}
	
	public static Vector2 randomPosition()
	{
		Vector2 randScreenPos = Vector2.one;
		randScreenPos.x = Random.Range(0, Screen.width);
		randScreenPos.y = Random.Range(0, Screen.height);
		return randScreenPos;
	}
	
	void randomSpeed()
	{
		int fps = Random.Range(4,8);
		spriteHandler.Play(fps);
		speed =   5.0f  * fps/8.0f;
		tweenPos.duration  = 0.65f * (2 - fps/8.0f);
	}
	// Update is called once per frame
	void Update () 
	{
		spriteHandler.Update();
		/*
		Vector3 direction = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
		direction.y = 0.0f;
		Quaternion lookRotation = Quaternion.LookRotation(direction);
		transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 3.0f);*/
		
		//mousePos = Input.mousePosition;
    	//screenPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, transform.position.z - Camera.main.transform.position.z));
		
		if(Vector3.Distance(target, transform.position) < 1.0f)
		{
			float rotationValue = 0;
			do{
			randomSpeed();
			target = Camera.main.ScreenToWorldPoint(randomPosition());
			target.z = transform.position.z;

			
			rotationValue = Mathf.Lerp(Mathf.Atan2((target.y - transform.position.y), (target.x - transform.position.x))* Mathf.Rad2Deg, transform.eulerAngles.z, Time.deltaTime);

			}while((rotationValue > 60 && rotationValue < 120) || (rotationValue > 220 &&  rotationValue < 300));
			return;
		}
		
		
		if(transform.eulerAngles.z < 90 || transform.eulerAngles.z > 270)
			renderChild.transform.localScale =  new Vector3(-1,1, 1);
		else
			renderChild.transform.localScale =  Vector3.one;
		
		Vector3 tmpRot = Vector3.zero;
		tmpRot.z = Mathf.Lerp(Mathf.Atan2((target.y - transform.position.y), (target.x - transform.position.x))* Mathf.Rad2Deg, transform.eulerAngles.z, Time.deltaTime);
    	transform.eulerAngles = tmpRot;
		
		transform.Translate(Vector3.right * Time.deltaTime * speed);
	}
}
